package com.wjb.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.wjb.springcloud.dao.StudentRepository;
import com.wjb.springcloud.pojo.Student;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

@RestController
public class StudentController {
    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private StudentRepository studentRepository;

//    @Autowired
//    private EurekaClient eurekaClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/simple/{id}",method = RequestMethod.GET)
    public Student findbyId(@PathVariable("id") Long id){
        for (int i=1;i<6;i++){
            Student s=new Student();
            s.setId((long)i);
            s.setAge(i+10);
            s.setBalance(i+100);
            s.setName("name"+i);
            s.setUsername("username"+i);
            studentRepository.save(s);
        }
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return studentRepository.getOne(id);
    }
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public Student getStudent(@RequestParam("id") Long id){
        for (int j=1;j<6;j++){
            Student s=new Student();
            s.setId((long)j);
            s.setAge(j+10);
            s.setBalance(j+100);
            s.setName("nameis"+j);
            s.setUsername("username"+j);
            studentRepository.save(s);
        }
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return studentRepository.getOne(id);
    }
//    @RequestMapping(value = "eureka-instance",method = RequestMethod.GET)
//    public String serviceUrl(){
//        InstanceInfo instanceInfo=eurekaClient.getNextServerFromEureka("USER-SERVICE", false);
//        return instanceInfo.getHomePageUrl();
//    }
}
